/**特别注意 本项目只能在真机环境有效**/
import {
  WaveView
} from '../../utils/wave.js'
Page({
  data: {
    wave: null,
    recorder: null
  },
  onLoad() {
    const query = this.createSelectorQuery();
    query.select(`#wave`)
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        const canvas = res[0].node
        const waveView = new WaveView({
          elem: canvas,
          width: wx.getSystemInfoSync().windowWidth,
          height: 100,
          scale: 1,
          linear1: [0, '#2ACF6F', 1, '#2ACF6F'],
          linear2: [0, '#2ACF6F', 1, '#2ACF6F']
        });
        this.setData({
          wave: waveView
        }, () => {
          this.data.wave.input(4096, 0)
        });
      })
    let recorder = wx.getRecorderManager()
    const audioCtx = wx.createWebAudioContext()
    const analyser = audioCtx.createAnalyser();
    recorder.onFrameRecorded(listener => {
      if (listener.isLastFrame) {
        console.log('soundIntensity', 0)
        this.data.wave.input(4096, 0)
      } else {
        audioCtx.decodeAudioData(listener.frameBuffer, buffer => {
          let source = audioCtx.createBufferSource()
          source.buffer = buffer
          source.connect(analyser)
          source.start()
          let n = new Uint8Array(analyser.frequencyBinCount)
          analyser.getByteTimeDomainData(n)
          let i = 0,
            r = 0,
            s = 0
          r = Math.max.apply(null, n)
          s = Math.min.apply(null, n)
          i = (r - s) / 128
          i = Math.round(i * 100 / 2)
          i = i > 100 ? 100 : i
          console.log(  listener.isLastFrame ? 0 : i,'--muisc分贝--' )
          this.data.wave.input(4096, listener.isLastFrame ? 0 : i, 16000)
        }, err => {
          console.error('decodeAudioData fail', err)
        })
      }
    })
    this.setData({
      recorder
    })
  },
  Record() {
    this.data.recorder.start({
      duration: 10000,
      sampleRate: 16000, //采样率
      numberOfChannels: 1, //录音通道数
      encodeBitRate: 96000, //编码码率
      format: 'mp3', //音频格式，有效值 aac/mp3
      frameSize: 1
    })
  }
})